package com.tro.mail.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
import com.tro.mail.dao.entity.MailInboxExample;
import com.tro.mail.util.MailStatus;
import com.tro.mail.vo.Message;

@Component
public class MailScoketHandler implements WebSocketHandler{
    public static final Map<String, WebSocketSession> userSocketSessionMap;
    @Autowired
	MailInboxManager inBoxManager;
    static {
        userSocketSessionMap = new HashMap<String, WebSocketSession>();
    }
    
    //握手实现连接后
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        Object user=webSocketSession.getAttributes().get("CONNECT_USER");
    	String CONNECT_USER = "";
    	if(user!=null){
    		CONNECT_USER=user.toString();
    	}
        if (userSocketSessionMap.get(CONNECT_USER) == null) {
            userSocketSessionMap.put(CONNECT_USER, webSocketSession);
        }
        //推送未读邮件条数数据
        MailInboxExample inBoxExample = new MailInboxExample();
		inBoxExample.createCriteria().andOwerUserIdEqualTo(CONNECT_USER).andForderIdEqualTo(MailStatus.INBOX_ID)
				.andIsReadEqualTo(MailStatus.NOT_READ);
		Integer NOT_READ_COUNT = inBoxManager.countByExample(inBoxExample);
		
        sendMessageToUser(CONNECT_USER, new TextMessage("NOT_READ:"+NOT_READ_COUNT));
    }

    //发送信息前的处理
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

        if(webSocketMessage.getPayloadLength()==0)return;
        Message msg= JSON.parseObject(webSocketMessage.getPayload().toString(),Message.class);  
        //发送Socket信息
        sendMessageToUser(msg.getToId(), new TextMessage(msg.getMessageText()));
    }

    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    /**
     * 关闭连接
     */
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        Iterator<Map.Entry<String,WebSocketSession>> iterator = userSocketSessionMap.entrySet().iterator();
        while(iterator.hasNext()){//遍历所有的连接
            Map.Entry<String,WebSocketSession> entry = iterator.next();
            if(entry.getValue().getAttributes().get("CONNECT_USER")==webSocketSession.getAttributes().get("CONNECT_USER")){
                userSocketSessionMap.remove(webSocketSession.getAttributes().get("CONNECT_USER"));
            }
        }
    }

    public boolean supportsPartialMessages() {
        return false;
    }

    //发送信息的实现
    public void sendMessageToUser(String uid, TextMessage message)
            throws IOException {
        WebSocketSession session = userSocketSessionMap.get(uid);
        if (session != null && session.isOpen()) {
            session.sendMessage(message);
        }
    }

}
